/*
 * @Author: xiaodong 565071984@qq.com
 * @Date: 2022-05-02 19:25:33
 * @LastEditors: 肖东 565071984@qq.com
 * @LastEditTime: 2022-05-17 16:07:58
 * @FilePath: /小票/src/store/modules/user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * @author https://gitee.com/chu1204505056/vue-admin-better （不想保留author可删除）
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import { getUserInfo, login } from '@/api/user'
import { title, tokenName } from '@/config'
import vm from '@/main.js'
import { resetRouter } from '@/router'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'
import Vue from 'vue'
const state = () => ({
  accessToken: getAccessToken(),
  username: '',
  avatar: '',
  userinfo: '',
  permissions: [],
})
const getters = {
  accessToken: (state) => state.accessToken,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  userinfo: (state) => state.userinfo,
  permissions: (state) => state.permissions,
}
const mutations = {
  setAccessToken(state, accessToken) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  setUserinfo(state, userinfo) {
    state.userinfo = userinfo
    // setUserinfo(userinfo)
  },
  setUsername(state, username) {
    state.username = username
  },
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
}
const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    const accessToken = data[tokenName]
    console.log(accessToken, '用户信息accessToken')
    if (accessToken) {
      const { username } = data
      commit('setAccessToken', accessToken)
      commit('setUserinfo', data)
      console.log(data, '用户信息')
      localStorage.setItem('userinfo', JSON.stringify(data))
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? vm.$t('login.goodMorning') /*'早上好'*/
          : hour <= 11
          ? vm.$t('login.goodMorning1') /*'上午好'*/
          : hour <= 13
          ? vm.$t('login.goodAfternoon') /*'中午好'*/
          : hour < 18
          ? vm.$t('login.goodAfternoon1') /*'下午好'*/
          : vm.$t('login.goodEvening') /*'晚上好'*/
      Vue.prototype.$baseNotify(
        `${vm.$t('login.weocomeToLogin')}${title}` /*'欢迎登陆'*/,
        `${thisTime}！`
      )
    } else {
      Vue.prototype.$baseMessage(
        `${vm.$t(
          'login.interfaceException'
        )}${tokenName}...` /*'登录接口异常，未正确返回'*/,
        'error'
      )
    }
  },
  async getUserInfo({ commit, state }) {
    const baseUserInfo = {
      permissions: ['admin'], //['admin']
      username: 'admin',
      avatar: 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif',
    }
    let userinfo = state.userinfo
    userinfo = Object.assign({}, { ...baseUserInfo }, { ...userinfo })
    const data = userinfo || (await getUserInfo(state.accessToken))
    if (!data) {
      Vue.prototype.$baseMessage(
        vm.$t('login.validationFailed') /*'验证失败，请重新登录...'*/,
        'error'
      )
      return false
    }
    let { permissions, username, avatar } = data
    if (permissions && username && Array.isArray(permissions)) {
      commit('setPermissions', permissions)
      commit('setUsername', username)
      commit('setAvatar', avatar)
      return permissions
    } else {
      Vue.prototype.$baseMessage(
        vm.$t('login.userInformationAbnormal') /*'用户信息接口异常'*/,
        'error'
      )
      return false
    }
  },
  async logout({ dispatch }) {
    // await logout(state.accessToken)
    await dispatch('resetAccessToken')
    await resetRouter()
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
